package com.quanquan.management.controller;

import DTO.PageDTO;
import base.BaseController;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quanquan.management.core.utils.AgentUtils;
import com.quanquan.management.core.utils.DecriptUtils;
import com.quanquan.management.dto.SysUserDTO;
import com.quanquan.management.entity.SysRoleUser;
import com.quanquan.management.entity.SysUser;
import com.quanquan.management.request.SysUserResquestBody;
import com.quanquan.management.service.SysRoleUserService;
import com.quanquan.management.service.SysUserService;
import enums.ResCodeEnum;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import request.PageRequestBody;
import utils.StringUtil;
import web.response.ResultBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author:lihonglinag
 * @date:2019-03-21 17:57
 * @version:v 1.0.0
 */
@Log4j2
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @PostMapping(path = "/login")
    public ModelAndView login(String username, String password) {
        Subject currentUser = SecurityUtils.getSubject();

        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtils.md5(password));
            if (!currentUser.isAuthenticated()) {
                token.setRememberMe(true);
                currentUser.login(token);// 验证角色和权限
            }
        } catch (Exception ex) {
            //用户名或密码错误
            return new ModelAndView("redirect:/login?error");
        }
        SysUser user = sysUserService.getSysUserByUserName(username);
        if (user != null) {
            user.setLastLoginIp(AgentUtils.getIpAddress(request));
            user.setLastLoginTime(new Date());
            sysUserService.save(user);
        }
        currentUser.getSession().setTimeout(10*60*60*1000);
        return new ModelAndView("redirect:/index.html");

    }


    @GetMapping(path = "/list")
    public String list(@RequestParam(required = false) Integer pageSize,
                       @RequestParam(required = false) Integer page,
                       @RequestParam(required = false) String keyword,
                       @RequestParam(required = false) String fromDate,
                       @RequestParam(required = false) String toDate, Model model) {
        if (null == pageSize) {
            pageSize = 10;
        }
        if (null == page) {
            page = 0;
        } else if (page > 0) {
            page = page - 1;
        }
        PageRequestBody requestBody = new PageRequestBody();
        requestBody.setPage(page);
        requestBody.setSize(pageSize);
        requestBody.setKeyword(keyword);
        requestBody.setToDate(toDate);
        requestBody.setFromDate(fromDate);
        PageDTO<SysUser> paged = sysUserService.getPaged(requestBody);
        model.addAttribute("pageObj",paged);
        return "sysUser/list";
    }


    @PostMapping("/save")
    public @ResponseBody
    ResultBody save(SysUserResquestBody requestBody) {
        String id = requestBody.getId();
        String roleId = requestBody.getRoleId();
        if (StringUtil.isEmpty(roleId)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(), "请选择用户角色");
        }
        String username = requestBody.getUsername();
        if (StringUtil.isEmpty(username)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(), "请输入用户名");
        }
        String password = requestBody.getPassword();
        try {
            SysUser sysUser = new SysUser();
            if (StringUtil.isNotEmpty(id)) {
                sysUser = sysUserService.getOne(requestBody.getId());
                if (StringUtil.isEmpty(password)) {
                    password = sysUser.getPassword();
                } else {
                    password = DecriptUtils.md5(password);
                }
                BeanUtil.copyProperties(requestBody, sysUser, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                sysUser.setPassword(password);
                sysUserService.save(sysUser);
                SysRoleUser byUserId = sysRoleUserService.findByUserId(sysUser.getId());
                byUserId.setRoleId(roleId);
                sysRoleUserService.save(byUserId);
            } else {
                if (StringUtil.isEmpty(password)) {
                    return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(), "请输入密码");
                }
                SysUser sysUserByUserName = sysUserService.getSysUserByUserName(username);
                if (null != sysUserByUserName) {
                    return new ResultBody(ResCodeEnum.FAIL.getCode(),"用户名已存在");
                }
                BeanUtil.copyProperties(requestBody, sysUser, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                sysUser.setRegTime(new Date());
                sysUser.setPassword(DecriptUtils.md5(password));
                SysUser save = sysUserService.save(sysUser);
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setUserId(save.getId());
                sysRoleUser.setRoleId(roleId);
                sysRoleUserService.save(sysRoleUser);
            }
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg());
        } catch (Exception e) {
            log.error(e.getMessage() + " 保存失败");
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
    }

    @GetMapping("/get/{id}")
    public @ResponseBody
    ResultBody findById(@PathVariable String id) {
        try {
            SysUserDTO dto = new SysUserDTO();
            SysUser user = sysUserService.getOne(id);
            BeanUtil.copyProperties(user, dto, true, CopyOptions.create().setIgnoreNullValue(true));
            String userId = user.getId();
            SysRoleUser userRole = sysRoleUserService.findByUserId(userId);
            dto.setRoleId(userRole.getRoleId());
            dto.setPassword("");
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), dto);
        } catch (Exception e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
    }

    @PostMapping("/update_password")
    public @ResponseBody
    ResultBody updatePassWord(SysUserResquestBody requestBody) {
        String id = requestBody.getId();
        String password = requestBody.getPassword();
        String oldPassword = requestBody.getOldPassword();
        if (StringUtil.isEmpty(oldPassword)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(), "请输入原密码");
        }
        if (StringUtil.isEmpty(password)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(), "请输入密码");
        }
        try {
            SysUser sysUser;
            if (StringUtil.isNotEmpty(id)) {



                sysUser = sysUserService.getOne(requestBody.getId());
                if (sysUser == null) {
                    return new ResultBody(ResCodeEnum.NO_DATA.getCode(), "未查询到用户");
                }
                if(!sysUser.getPassword().equals(DecriptUtils.md5(oldPassword))){
                    return new ResultBody(ResCodeEnum.FAIL.getCode(), "原密码错误");
                }
                BeanUtil.copyProperties(requestBody, sysUser, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                sysUser.setRegTime(new Date());
                sysUser.setPassword(DecriptUtils.md5(password));
                sysUserService.save(sysUser);
            }
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg());
        } catch (Exception e) {
            log.error(e.getMessage() + " 保存失败");
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
    }

    @GetMapping("/delete/{id}")
    public @ResponseBody
    ResultBody delete(@PathVariable String id) {
        try {
            List<SysUser> list = new ArrayList<>();
            SysUser one = sysUserService.getOne(id);
            list.add(one);
            sysUserService.deleteInBatch(list);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg());
        } catch (Exception e) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
    }


}
